package net.sk.mina.imagine.server;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import net.sk.cam.FrameHeader;
import net.sk.cam.ImageResponse;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import dao.hb.ODevice;

public class ImageThread implements Runnable {
	private final int loop_count = 50000;
	private final int loop_span = 1000;
	private final int loop_len = 6;
	private final int loop_heart = 5;
	
	private IoHandlerAdapter pl;
	private IoSession s;
	private ODevice od;
	
	public ImageThread(IoHandlerAdapter pl,IoSession s,ODevice od){
		this.pl =pl;
		this.s = s;
		this.od = od;
	}
	private String generateString(IoSession session, int length){
		return ImageServerIoHandler.generateString(session, length);
	}
    private BufferedImage createImage(int width,int height, String text) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
        Graphics graphics = image.createGraphics();
        graphics.setColor(Color.DARK_GRAY);
        graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
        Font serif = new Font("serif", Font.PLAIN, 30);
        graphics.setFont(serif);
        graphics.setColor(Color.WHITE);
        graphics.drawString(text, 10, 50);
        return image;  	
    }

	@Override
	public void run() {
		// TODO Auto-generated method stub
        //c4w
        for(int i=0; i<loop_count; i++){
            //发送心跳帧
            if(i % loop_heart ==0){
                FrameHeader fht = new FrameHeader();
                if(od!=null){
                	fht.setDevice_no(od.getId());
                }
                fht.setFrame_type(FrameHeader.FRAME_TYPE_HEART);
                fht.setLen(0);
                ImageResponse rt = new ImageResponse(fht,null);
                s.write(rt);                 	
            }else{
                String text1 = generateString(s, loop_len);
                BufferedImage image1 = createImage(200,200, text1);
                FrameHeader fh = new FrameHeader();
                if(od!=null){
                	fh.setDevice_no(od.getId());
                }
                fh.setFrame_type(FrameHeader.FRAME_TYPE_NORMAL);
                ImageResponse response = new ImageResponse(fh,image1);
                s.write(response);      
            }
            try {
				Thread.sleep(loop_span);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

	}

}
